import Fingerprint2 from "fingerprintjs2";
// import Push from "push.js";
import { getQueryVariable } from "./utils";

window.lifeCheckLock = false;
function makeLinkLife(clientUtils) {   
    if (!window.lifeCheckLock) {
        window.lifeCheckLock = true;
        clientUtils.send(ws, "firstwoshou", {
            from: { 
                userID: window.currentUser.userID
            },
            to: window.talkTo
        }); 
    }
}

export default function (app, currentUser, data, clusterize, createUserCard, appMethods, clientUtils) {
    var checklifetimeout = null;


    window.startWsConnection = function () {
        var myID;
        var selectedPeerID;
        var users = {};
        var file; // file to be sent;

        window.gloablwsurl = `ws://${globalServerAddress}:9700/room` + getQueryVariable("room", 1);

        window.ws = new WebSocket(window.gloablwsurl);

        ws.onopen = evt => {
            if (window.filer) {
                window.filer.signalingChannel = window.ws;
            }
            console.log('webSocket connected');
            new Fingerprint2().get(function(result, components){
                // console.log(components);
                clientUtils.send(ws, "register", {
                    fingerprint: result
                });
            });

        };

        ws.onmessage = msgevent => {       
            if (typeof msgevent.data === "string") {

                try {
                    var msgObj = JSON.parse(msgevent.data);
                } catch (e){
                    console.log('Oops, unknown msg: ', e);
                    return
                }
                switch (msgObj.msgType) {
                    case "newUser":                    
                        console.log('new msg from ws server: ', msgObj);

                        if (window.currentUser && window.currentUser.userID === msgObj.userID ) {
                            console.log("你不能和自己对话");
                            break;
                        }

                        users[ msgObj.userID ] = true;
                        // addPeers([msgObj.userID]);
                        console.log('new comer: ', msgObj.userID);                        
                        // clusterize.append(createUserCard(msgObj.userID, `用户 ${msgObj.userID}`));
                        app.header = `${msgObj.userID}`;
                        if ( !window.talkTo || !window.talkTo[msgObj.userID]) {
                            window.talkTo = msgObj;
                        }            
                                            
                        if (!checklifetimeout) {
                            window.lifeCheckLock = false;
                            checklifetimeout = setTimeout(function() {              
                                makeLinkLife(clientUtils);     
                            }, 1000);                            
                        }
                        break;
    
                    case "removeUser":
                        console.log('new msg from ws server: ', msgObj);

                        if (window.currentUser && window.currentUser.userID === msgObj.userID ) {
                            console.log("你不能和删除自己");
                            break;
                        }

                        delete users[ msgObj.userID ];
                        delete data[ msgObj.userID ];
                        console.log('remove user: ', msgObj.userID);
    
                        if (getQueryVariable("multi")) {
                            var arr = [];
                            for (var k in data) {
                                arr.push(data[k]);
                            }
                            clusterize.update(arr);
                        } else {
                            app.header = ``;
                        }

                        // 清除定期查询
                        clearTimeout(checklifetimeout);
                        checklifetimeout = null;
                        break;
    
                    case "profile":
                        console.log('new msg from ws server: ', msgObj);
                        // msgObj.peersIDS.forEach(p => {
                        //     users[p] = true
                        // });
                        console.log('profile: my uid: ', msgObj.userID, ', peersID: ', msgObj.peersID);
                        currentUser = msgObj;
    
                        window.currentUser = currentUser;
                        if (window.filer) {
                            window.filer.myID = myID = msgObj.userID;
                        }
                        window.myID = myID;
                        window.globalUsers = users;
                        // addPeers(msgObj.peersID);
    
                        // clusterize.append(createUserCard(msgObj.userID, `我 ${msgObj.userID}`));
    
                        if (getQueryVariable("multi")) {
                            // 多人模式下
                            // 添加除了自己以外的已经存在的用户
                            msgObj.users.forEach(user => {
                                var title = user.userID + "";
                                if (msgObj.userID === user.userID) {
    
                                } else {
                                    title = "用户 " + title;
                                    clusterize.append(createUserCard(user.userID, title));
                                }
                                users[user.userID] = true;
                            });
                        } else {
                            // 单聊模式下
                            msgObj.users.forEach(user => {
                                var title = user.userID + "";
                                if (msgObj.userID === user.userID) {
    
                                } else {                         
                                    app.header = `${title}`;
                                    window.talkTo = user;
                                }
                                users[user.userID] = true;
                            });

                            checklifetimeout = setTimeout(function() {              
                                makeLinkLife(clientUtils);     
                            }, 1000);
                        }
                        break;
    
                    case "signaling":
                        console.dir(msgObj);
                        window.filer.handleSignaling(msgObj);
                        break;
    
                    case "chat":
                        console.log('new msg from ws server: ', msgObj);
                        // appMethods.appendMessage(
                        //     msgObj.origin,
                        //     "left",
                        //     'https://static.zhilizhili.com/static/3828461873613813290.jpg',
                        //     "sdsds",
                        //     function (createElement) {
                        //         return [
                        //             createElement(
                        //                 'div',
                        //                 {
                        //                     domProps: {
                        //                         innerHTML: msgObj.origin.content
                        //                     }
                        //                 }
                        //             )
                        //         ];
                        //     },
                        //     ''
                        // );

                        if (window.onAppMessage) {
                            window.onAppMessage(window.AUI.app.messageType.CHAT, msgObj);
                        }
                        break;

                    case "duifangzhaoni":
                                            
                        clientUtils.send(ws, "iamlife", {
                            from: { 
                                userID: window.currentUser.userID
                            },
                            to: window.talkTo
                        });
                        break;
    
                    case "duifangislife":
                        
                        console.log('------------------------------------');
                        console.log("好的");
                        console.log('------------------------------------');


                        window.lifeCheckLock = false;
                        checklifetimeout = setTimeout(function() {              
                            makeLinkLife(clientUtils);     
                        }, 60000);
                        break;

                    case "duifangguale":

                        console.log('------------------------------------');
                        console.log("对方挂了");
                        console.log('------------------------------------');

                        window.lifeCheckLock = false;
                        if (app.header) {
                            app.header = "";
                        }

                        break;
                        
                    default: console.log('Oops. unknown msg: ', msgObj)
                }                

            } else {
                window.AUI.app.globalHandleFile(msgevent);
            }       
        };
    }
}